package com.uinnova.product.eam.service.utils;

import com.binary.core.io.support.FileResource;
import com.uinnova.product.eam.base.model.FileProResource;
import com.uinnova.product.eam.base.model.FileResourceMeta;
import com.uinnova.product.eam.base.util.ResourceUtil;
import com.uino.util.rsm.RsmUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileUtils {

    private static RsmUtils rsmUtils;

    private static Logger logger = LoggerFactory.getLogger(ZipFileUtils.class);

    public ZipFileUtils(RsmUtils rsmUtils){
        this.rsmUtils = rsmUtils;
    }

    public ZipFileUtils(){}

    /**
     * 压缩多个文件成一个zip文件
     * @param srcFile：源文件列表
     */
    private static void zipFiles(File[] srcFile, File file){
        byte[] buf=new byte[1024];
        // 新压缩的文件夹地址
        try (ZipOutputStream out=new ZipOutputStream(Files.newOutputStream(file.toPath()))){
            //ZipOutputStream类：完成文件或文件夹的压缩
            for(int i=0; i < srcFile.length; i++){
                try(FileInputStream in=new FileInputStream(srcFile[i])){
                    out.putNextEntry(new ZipEntry(srcFile[i].getName()));
                    int len;
                    while((len=in.read(buf)) > 0){
                        out.write(buf,0,len);
                    }
                    out.closeEntry();
                }
            }
            out.close();
            logger.info("压缩完成.");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 压缩多个文件成一个zip文件
     * @param srcFiles：源文件列表
     */
    private static void zipFileResources(FileProResource[] srcFiles, File file){
        final Set<String> names = new HashSet<>(srcFiles.length);
        byte[] buf=new byte[1024];
        // 新压缩的文件夹地址
        try(ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(file.toPath()))) {
            //ZipOutputStream类：完成文件或文件夹的压缩
            String fileName = "";
            for (FileProResource fileResource : srcFiles) {
                fileName = fileResource.getFileName();
                if(names.contains(fileName)){
                    String docName = fileName.substring(0, fileName.lastIndexOf("."));
                    String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                    fileName = (docName +"("+ names.size() + ")." + fileType);
                }
                names.add(fileName);
                try(FileInputStream in = new FileInputStream(fileResource.getFile())){
                    out.putNextEntry(new ZipEntry(fileName));
                    int len;
                    while((len=in.read(buf)) > 0){
                        out.write(buf,0,len);
                    }
                }
                out.closeEntry();
            }
            out.close();
            logger.info("压缩完成.");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public static FileResource zipToResource(List<FileResourceMeta> fileResourceMetas, String fileName){
        FileProResource[] files = ResourceUtil.installFiles(fileResourceMetas, each -> new FileProResource(new File(each.getResPath()), each.getName()));
        File file = new File(fileName);
        zipFileResources(files, file);
        rsmUtils.uploadRsmFromFile(file);
        return new FileResource(file);
    }

}
